<?php

/**
 * 联系信息模型
 */
class Contact_model extends CI_Model {
    
    const TN = "contacts";
    
    /**
     * 执行批量插入后，保存所有记录id，用逗号隔开
     * @var type 
     */
    private $_ids;
    
    /**
     * 
     * @param type $conditions
     * @param type $per_page 默认0表示取所有记录
     * @param type $page
     * @return array
     */
    public function fetch_array($conditions, $per_page = 0, $page = 0) {
        $this->_set_where($conditions);
        if ($per_page > 0) {
            $offset = ($page - 1) * $per_page;
            $this->db->limit($per_page, $offset);
        }
        $this->db->order_by('ct_id', 'asc');

        return $this->db->get(self::TN)->result_array();
    }
    
    private function _set_where($conditions) {
        if (isset($conditions['ids'])) {
            $this->db->where_in('ct_id', explode(',', $conditions['ids']));
        }
    }
    
    /**
     * 批量插入
     * @param type $contacts
     */
    public function insert_batch($contacts) {
        $this->_ids = '';
        foreach ($contacts as $contact) {
            $this->db->insert(self::TN, $contact);
            $this->_ids .= $this->db->insert_id() . ',';
        }
    }
    
    /**
     * 返回批量插入生成的记录id，用逗号隔开，调用insert_batch之后立刻调用此函数
     * @return type
     */
    public function insert_ids() {
        return trim($this->_ids, ",");
    }
}

